package com.gopay.webtest.controller;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gopay.webtest.controller.base.BaseController;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.webtest.util.BaseSign;
import com.gopay.webtest.util.DateUtils;
import com.gopay.webtest.util.PropertyUtil;
import com.gopay.webtest.vo.CommonResp;
import com.gopay.webtest.vo.GuaranteeApply;
import com.gopay.webtest.vo.GuaranteeCancel;
import com.gopay.webtest.vo.GuaranteeComplete;
import com.gopay.webtest.xml.XmlDao;

@RequestMapping("/guarantee")
@Controller
public class GuaranteePaymentController extends BaseController {

    private static Logger logger = Logger.getLogger(GuaranteePaymentController.class);
    private static String XML_FILE = "guaranteepay";
    private static String XML_FILE_CANCEL = "guaranteepaycancel";
    private static String XML_FILE_COMPLETE = "guaranteepaycomplete";
    private static String PAY_APPLY = "payapply";
    private static String PAY_CANCEL = "paycancel";
    private static String PAY_COMPLETE = "paycomplete";
    private static String VERSOIN = "2.0";
    private static String CHARSET_GBK = "1";

    private XmlDao xmlDao = null;

    private BaseSign trans9999Handler;

    private BaseSign trans2002Handler;

    private BaseSign trans2003Handler;

    @RequestMapping("/apply")
    public ModelAndView applyGuarantee(HttpServletRequest request, HttpServletResponse response) {

        ModelAndView mv = new ModelAndView();

        // 加载xml数据到
        try {
            Map<String, String> map = this.xmlDao.readData4Map(XML_FILE, PAY_APPLY);
            if(map.containsKey("gopayServerTime")){
                map.remove("gopayServerTime");
                map.put("gopayServerTime", DateUtils.format(new Date(),"yyyyMMddHHmmss"));
            }
            if(map.containsKey("tranDateTime")){
                map.remove("tranDateTime");
                map.put("tranDateTime", DateUtils.format(new Date(),"yyyyMMddHHmmss"));
            }
            
            mv.addObject("payinfo", map);
            mv.setViewName("gopay.webtest.guarantee_payment_apply");
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return mv;
    }

    
    @RequestMapping("/cancel")
    public ModelAndView cancelGuarantee() {

        ModelAndView mv = new ModelAndView();

        try {
            Map<String, String> map = this.xmlDao.readData4Map(XML_FILE_CANCEL, PAY_CANCEL);
            if(map.containsKey("gopayServerTime")){
                map.remove("gopayServerTime");
                map.put("gopayServerTime", DateUtils.format(new Date(),"yyyyMMddHHmmss"));
            }
            if(map.containsKey("tranDateTime")){
                map.remove("tranDateTime");
                map.put("tranDateTime", DateUtils.format(new Date(),"yyyyMMddHHmmss"));
            }
            
            mv.setViewName("gopay.webtest.guarantee_payment_cancel");
            mv.addObject("payinfo", map);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return mv;
    }

    @RequestMapping("/complete")
    public ModelAndView completeGuarantee() {

        ModelAndView mv = new ModelAndView();
        try {
            Map<String, String> map = this.xmlDao.readData4Map(XML_FILE_COMPLETE, PAY_COMPLETE);
            if(map.containsKey("gopayServerTime")){
                map.remove("gopayServerTime");
                map.put("gopayServerTime", DateUtils.format(new Date(),"yyyyMMddHHmmss"));
            }
            if(map.containsKey("tranDateTime")){
                map.remove("tranDateTime");
                map.put("tranDateTime", DateUtils.format(new Date(),"yyyyMMddHHmmss"));
            }
            
            mv.setViewName("gopay.webtest.guarantee_payment_complete");
            mv.addObject("payinfo", map);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return mv;
    }

    @RequestMapping("/apply/submit")
    public ModelAndView submitApplyGuarantee(GuaranteeApply applay) {

        ModelAndView mv = new ModelAndView("gopay.webtest.guarantee_payment_apply_submit");

        /*** 对表单数据进行处理 begin */

        /*** 判断担保支付的版本 */
        if (!VERSOIN.equals(applay.getVersion())) {

            CommonResp resp = new CommonResp();

            PropertyUtil.copyProperty(applay, resp);

            resp.setRespCode("MR03");

            resp.setMsgExt("担保支付2.0交易：版本号只支持2.0");

            mv.addObject("payinfo", resp);

            if (!CHARSET_GBK.equalsIgnoreCase(applay.getCharset())) {

                mv.setViewName("gopay.webtest.front_res_info_trans");

            } else {

                mv.setViewName("gopay.webtest.front_res_info_trans_gbk");
            }
            return mv;
        }

        String bgUrl = applay.getBackgroundMerUrl();
        String ftUrl = applay.getFrontMerUrl();

        if (bgUrl != null && !"".equals(bgUrl))
            applay.setBackgroundMerUrl(bgUrl + "?id=" + applay.getVerficationCode());
        if (ftUrl != null && !"".equals(ftUrl))
            applay.setFrontMerUrl(ftUrl + "?id=" + applay.getVerficationCode());

        try {
            // 进行加签
            trans9999Handler.sign(applay.getTranCode(), "signType", "signValue", applay, getRequest());
        } catch (Exception e) {

            e.printStackTrace();

            CommonResp resp = new CommonResp();

            PropertyUtil.copyProperty(applay, resp);

            resp.setRespCode("MR01");

            resp.setMsgExt("验证签名失败");

            mv.addObject("payinfo", resp);

            if (!CHARSET_GBK.equalsIgnoreCase(applay.getCharset())) {

                mv.setViewName("gopay.webtest.front_res_info_trans");

            } else {

                mv.setViewName("gopay.webtest.front_res_info_trans_gbk");
            }
            return mv;

        }

        mv.addObject("payinfo", applay);

        /*** 对表单数据进行处理 end */
        // gbk
        if (!CHARSET_GBK.equalsIgnoreCase(applay.getCharset())) {
            mv.setViewName("gopay.webtest.guarantee_payment_apply_submit");
        } else {
            mv.setViewName("gopay.webtest.guarantee_payment_apply_submit_gbk");
        }

        mv.addObject("payinfo", applay);
        return mv;
    }

    @RequestMapping("/cancel/submit")
    public ModelAndView submitCancelGuarantee(GuaranteeCancel cancel) {

        ModelAndView mv = new ModelAndView("gopay.webtest.guarantee_payment_cancel_submit_gbk");

        /*** 对表单数据进行处理 begin */

        /*** 判断担保支付的版本 */
        if (!VERSOIN.equals(cancel.getVersion())) {

            CommonResp resp = new CommonResp();

            PropertyUtil.copyProperty(cancel, resp);

            resp.setRespCode("MR03");

            resp.setMsgExt("担保支付2.0交易：版本号只支持2.0");

            mv.addObject("payinfo", resp);

            if (!CHARSET_GBK.equalsIgnoreCase(cancel.getCharset())) {
                mv.setViewName("gopay.webtest.front_res_info_trans");
            } else {
                mv.setViewName("gopay.webtest.front_res_info_trans_gbk");
            }
            return mv;
        }

        try {
            // 进行加签
            trans2003Handler.sign(cancel.getTranCode(), "signType", "signValue", cancel, getRequest());
        } catch (Exception e) {

            CommonResp resp = new CommonResp();

            PropertyUtil.copyProperty(cancel, resp);

            resp.setRespCode("MR01");

            resp.setMsgExt("验证签名失败");

            mv.addObject("payinfo", resp);

            e.printStackTrace();

            if (!CHARSET_GBK.equalsIgnoreCase(cancel.getCharset())) {
                mv.setViewName("gopay.webtest.front_res_info_trans");
            } else {
                mv.setViewName("gopay.webtest.front_res_info_trans_gbk");
            }
            return mv;

        }

        mv.addObject("payinfo", cancel);

        /*** 对表单数据进行处理 end */
        // gbk
        if (!CHARSET_GBK.equalsIgnoreCase(cancel.getCharset())) {
            mv.setViewName("gopay.webtest.guarantee_payment_cancel_submit");
        } else {
            mv.setViewName("gopay.webtest.guarantee_payment_cancel_submit_gbk");
        }

        mv.addObject("payinfo", cancel);
        return mv;
    }

    @RequestMapping("/complete/submit")
    public ModelAndView submitCompleteGuarantee(GuaranteeComplete complete, Errors error) {

        ModelAndView mv = new ModelAndView("gopay.webtest.guarantee_payment_complete_submit");

        /*** 对表单数据进行处理 begin */

        /*** 判断担保支付的版本 */
        if (!VERSOIN.equals(complete.getVersion())) {

            CommonResp resp = new CommonResp();

            PropertyUtil.copyProperty(complete, resp);

            resp.setRespCode("MR03");

            resp.setMsgExt("担保支付2.0交易：版本号只支持2.0");

            mv.addObject("payinfo", resp);

            if (!CHARSET_GBK.equalsIgnoreCase(complete.getCharset())) {
                mv.setViewName("gopay.webtest.front_res_info_trans");
            } else {
                mv.setViewName("gopay.webtest.front_res_info_trans_gbk");
            }
            return mv;
        }

        try {
            // 进行加签
            trans2002Handler.sign(complete.getTranCode(), "signType", "signValue", complete, getRequest());
        } catch (Exception e) {

            CommonResp resp = new CommonResp();

            PropertyUtil.copyProperty(complete, resp);

            resp.setRespCode("MR01");

            resp.setMsgExt("验证签名失败");

            mv.addObject("payinfo", resp);

            e.printStackTrace();

            if (!CHARSET_GBK.equalsIgnoreCase(complete.getCharset())) {
                mv.setViewName("gopay.webtest.front_res_info_trans");
            } else {
                mv.setViewName("gopay.webtest.front_res_info_trans_gbk");
            }
            return mv;
        }

        mv.addObject("payinfo", complete);

        /*** 对表单数据进行处理 end */
        // gbk
        if (!CHARSET_GBK.equalsIgnoreCase(complete.getCharset())) {
            mv.setViewName("gopay.webtest.guarantee_payment_complete_submit_gbk");
        } else {
            mv.setViewName("gopay.webtest.guarantee_payment_complete_submit");
        }

        mv.addObject("payinfo", complete);
        return mv;
    }

    public XmlDao getXmlDao() {
        return xmlDao;
    }

    @Autowired
    public void setXmlDao(XmlDao xmlDao) {
        this.xmlDao = xmlDao;
    }

    public BaseSign getTrans9999Handler() {
        return trans9999Handler;
    }

    @Resource(name = "trans9999Handler")
    public void setTrans9999Handler(BaseSign trans9999Handler) {
        this.trans9999Handler = trans9999Handler;
    }

    public BaseSign getTrans2002Handler() {
        return trans2002Handler;
    }

    @Resource(name = "Trans2002Handler")
    public void setTrans2002Handler(BaseSign trans2002Handler) {
        this.trans2002Handler = trans2002Handler;
    }

    public BaseSign getTrans2003Handler() {
        return trans2003Handler;
    }

    @Resource(name = "trans2003Handler")
    public void setTrans2003Handler(BaseSign trans2003Handler) {
        this.trans2003Handler = trans2003Handler;
    }

}
